// pages/yunku/order_detail.js
var App = getApp();
let status = '';
var remainMoney = 0;//使用余额
Page({

  /**
   * 页面的初始数据
   */
  data: {
    no: '',
    order_id: '',
    order_time: '',
    goodsList: [],
    totalAmount: 0,//合计金额
    orderType: 0,//是否是未确认订单
    type: 0,
    source:'',
    address:'',
    user_name:'',
    user_phone:'',
    all_number:0,

    paymentBlock:false,
    orderMoney:'0.00', //订单金额
    accountMoney:'0.00', //余额
    payChecked:false,
    orderStatus:'',
    showConfirm: false, //显示确认收货弹窗
    recive_time:'', //接受时间
    useMoney:'',
    useQuan:'0.00',
    useVipMoney:'0.00'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      no: options.order_no,
      type: options.type,
      source: options.source
    })
    status = options.type;
    this.getSuplymentDetail();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  
  // 取消订单
  onCancelOrder: function (e) {
    let order_no = e.currentTarget.dataset.no;
    let that = this;
    wx.showModal({
      title: '确认提示',
      content: '是否确认取消订单？',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: App.data.globalAPI + '/order/mall/cancel',
            data: {
              token: wx.getStorageSync('token'),
              order_no: order_no,
            },
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            success(res) {
              if (res.data.error == 0) {
                wx.showToast({
                  title: '订单取消成功!',
                  duration: 800
                })
                that.setData({
                  orderStatus: 3,
                  orderType:3,
                  paymentBlock: false
                })
                var curPageArr = getCurrentPages();
                var page = curPageArr[curPageArr.length - 2];
                page.setData({
                  cloudList: []
                })
                page.getCloudList();
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  duration: 800
                })
              }
            }
          })
        }
      }
    })
  },
  //获取订单详情
  getSuplymentDetail: function () {
    let that = this;
    let index = that.data.currentTab;
    wx.request({
      url: App.data.globalAPI + '/order/mall/getdetail',
      data: {
        token: wx.getStorageSync('token'),
        order_no: that.data.no
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          let data = res.data.data;
          let all= 0;
          for (var i = 0; i < data.goods.length;i++){
            all += parseInt(data.goods[i].number)
          }
          that.setData({
            no: data.order_no,
            order_id: data.order_no,
            order_time: App.timeTransformat(data.create_time),
            goodsList: data.goods,
            totalAmount: data.pay,//合计金额
            orderType: data.order_status,//是否是未确认订单
            type: data.order_status,
            address: data.address,
            user_name: data.user_name,
            user_phone: data.user_phone,
            all_number: all,
            orderStatus: data.order_status,
            recive_time: data.complete_time,
            useMoney: data.money_pay,
            useQuan: data.coupon_ident == '' ? '0.00' : parseFloat(data.coupon_ident).toFixed(2),
            useVipMoney: data.vip_order_price
          })
          wx.hideLoading();
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 600
          })
        }
      }
    })
  },

  // 关闭支付弹窗
  hidePayModal: function () {
    this.setData({
      paymentBlock: false,
      payChecked: false,
      noAddress: false
    })
  },

  //余额开关
  aliPaySwitch: function () {
    if (this.data.accountMoney == 0) {
      return false;
    }
    this.setData({
      payChecked: !this.data.payChecked
    })

    let orderMoney = this.data.orderMoney;//订单金额
    let yueMoney = this.data.accountMoney;//账户余额

    if (this.data.payChecked) {//使用余额
      if (parseFloat(yueMoney) > orderMoney) {
        remainMoney = parseFloat(orderMoney);
        orderMoney = 0;  
      } else {
        remainMoney = yueMoney;
        orderMoney = parseFloat(orderMoney) - parseFloat(yueMoney);
      }
    }else{
      remainMoney = 0;
      orderMoney = parseFloat(this.data.totalAmount);
    }
    this.setData({
      orderMoney: parseFloat(orderMoney).toFixed(2)
    })
  },

  //提交支付
  payMethod: function () {
    let that = this;
    let payWay = '';
    let useYue = 0;//使用的余额
    if (that.data.payChecked && that.data.accountMoney > 0 && that.data.orderMoney == 0) {
      payWay = 'account';
    } else if (that.data.payChecked && that.data.accountMoney > 0 && that.data.orderMoney > 0) {
      payWay = 'mixed';
    } else if (that.data.orderMoney == 0) {
      payWay = 'account';
    } else {
      payWay = 'online';
    }

    wx.request({
      url: App.data.globalAPI + '/order/mall/pay',
      data: {
        token: wx.getStorageSync('token'),
        pay_type: payWay,//在线支付: online 余额支付: account 混合支付: mixed,
        pay_method: payWay == 'account' ? 'account' : 'wxlite',
        order_no: that.data.order_id,
        pay: parseFloat(that.data.totalAmount).toFixed(2), //实付款
        account_pay: remainMoney,//余额支付金额 
        online_pay: that.data.orderMoney,//在线支付金额 
        client_type: 'wxlite'
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          var payArr = res.data.data.pay;
          var orderArr = res.data.data.order;
          if (payWay == 'account') {
            wx.showToast({
              title: '支付成功！'
            })
            that.setData({
              orderStatus: 4,
              orderType:4,
              paymentBlock: false
            })
            var curPageArr = getCurrentPages();
            var page = curPageArr[curPageArr.length - 2];
            page.setData({
              cloudList: []
            })
            page.getCloudList();
            App.getTokenLogin();//更新用户信息
            return false;
          }
          wx.requestPayment({
            timeStamp: payArr.timeStamp,
            nonceStr: payArr.nonceStr,
            package: payArr.package,
            signType: payArr.signType,
            paySign: payArr.paySign,
            success(res) {
              that.setData({
                orderStatus:4,
                orderType:4,
                paymentBlock:false
              })
              var curPageArr = getCurrentPages();
              var page = curPageArr[curPageArr.length - 2];
              page.setData({
                cloudList: []
              })
              page.getCloudList();
              App.getTokenLogin();//更新用户信息
            },
            fail(res) {
              wx.showToast({
                icon: 'none',
                title: '支付已取消'
              })
              that.setData({
                paymentBlock: false
              })
            }
          })
        }
        else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }

      }, fail(res) {
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      }
    })
  },

  //钱包金额
  getMoneyTotal: function () {
    wx.showLoading({
      title: '加载中',
    })
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/users/wallet/info',
      data: {
        token: wx.getStorageSync('token')
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          that.setData({
            accountMoney: parseFloat(res.data.data.money).toFixed(2)
          })

          if (that.data.accountMoney>0) {//使用余额
            that.setData({
              payChecked:true
            })
            let orderMoney = that.data.orderMoney;//订单金额
            let yueMoney = that.data.accountMoney;//账户余额
            if (parseFloat(yueMoney) > orderMoney) {
              remainMoney = parseFloat(orderMoney);
              orderMoney = 0;
            } else {
              remainMoney = yueMoney;
              orderMoney = parseFloat(orderMoney) - parseFloat(yueMoney);
            }
            that.setData({
              orderMoney: parseFloat(orderMoney).toFixed(2)
            })
          } 
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
        wx.hideLoading();
      },
      fail(res) {
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '网络异常，请稍后重试！',
          showCancel: false,
          success(res) {
          }
        })
      }
    })
  },

  //继续支付
  goOnpayOrder:function(){
    this.setData({
      payChecked: true,
      paymentBlock:true,
      orderMoney: this.data.totalAmount
    })
    this.getMoneyTotal()
  },

  // 确认送达弹窗
  onConfirmlOrder: function (e) {
    this.setData({
      showConfirm: true
    })
  },

  // 关闭确认送达
  closeSendWin: function () {
    this.setData({
      showConfirm: false
    })
  },

  // 确认送达
  onSendHandle: function () {
    let that = this;
    wx.request({
      url: App.data.globalAPI + '/order/mall/confirm',
      data: {
        token: wx.getStorageSync('token'),
        order_no: that.data.no,
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        if (res.data.error == 0) {
          wx.showToast({
            title: '已成功收货！',
            duration: 800
          })
          that.setData({
            showConfirm:false,
            orderStatus: 2,
            orderType: 2,
            recive_time: res.data.data
          })
          var curPageArr = getCurrentPages();
          var page = curPageArr[curPageArr.length - 2];
          if (page.route == 'pages/mine/order/box_order') {
            page.setData({
              cloudList: []
            })
            page.getCloudList();
          }
          
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 800
          })
        }
      }, fail() {
        wx.showToast({
          title: '网络异常，请稍后重试！',
          icon: 'none',
          duration: 800
        })
      }
    })
  }

  
})